<?php

namespace app\admin\controller;

use app\admin\BaseController;

class UserController extends BaseController
{
    /**
     * @Description 用户列表
     *
     * @return void
     */
    public function listAction()
    {
        try{
            $post = $this->post;
            $params = $this->_get_cond($post);

            $res = $this->app->userService->getLists($params, $this->post['page'], $this->post['pagesize']);

            $data['lists'] = [];
            foreach($res as $key=>$vo){
                $arr = [];
                $arr['userId'] = $vo->userId;
                $arr['userName'] = $vo->userName;
                $arr['realName'] = $vo->realName;
                $arr['phone'] = $vo->phone;
                $arr['uniCode'] = $vo->uniCode;
                $arr['openid'] = $vo->account;
                $arr['gender'] = $vo->gender;
                $arr['headImg'] = $vo->headImg;
                $arr['provinceName'] = $vo->provinceCode?$vo->province->provinceName:'';
                $arr['cityName'] = $vo->cityCode?$vo->city->cityName:'';
                $arr['universityName'] = $vo->universityId?$vo->university->universityName:'';
                $arr['totalCredit'] = $vo->totalCredit;
                $arr['currentCredit'] = $vo->currentCredit;
                $arr['donateCredit'] = $vo->donateCredit;
                $arr['availCredit'] = bcsub($vo->totalCredit, $vo->donateCredit);
                $arr['status'] = $vo->status;
                $arr['statusText'] = $vo->getStatusText();
                $arr['createdAt'] = $vo->createdAt;
                $data['records'][] = $arr;
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($res);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * @Description     用户详情
     * @param  [type] $id
     *
     * @return void
     */
    public function detailAction($id)
    {
        try{
            $user = $this->app->userService->getUserById($id);

            $this->app->userService->createUniCode($user);

            $data['userId'] = $user->userId;
            $data['userName'] = $user->userName;
            $data['realName'] = $user->realName;
            $data['phone'] = $user->phone;
            $data['openid'] = $user->openid;
            $data['gender'] = $user->gender;
            $data['headImg'] = $user->headImg;
            $data['provinceName'] = $user->provinceCode?$user->province->provinceName:'';
            $data['cityName'] = $user->cityCode?$user->city->cityName:'';
            $data['totalCredit'] = $user->totalCredit;
            $data['currentCredit'] = $user->currentCredit;
            $data['donateCredit'] = $user->donateCredit;
            $data['availCredit'] = bcsub($user->totalCredit, $user->donateCredit);
            $data['universityId'] = $user->universityId;
            $data['universityName'] = $user->universityId?$user->university->universityName:'';
            $data['major'] = $user->major;
            $data['grade'] = $user->getGradeText();
            $data['year'] = $user->year;
            $data['uniCode'] = $user->uniCode;
            $data['availCredit'] = bcsub($user->totalCredit, $user->donateCredit);
            $data['status'] = $user->status;
            $data['statusText'] = $user->getStatusText();
            $data['createdAt'] = $user->createdAt;
            return json(['code' => 200, 'message' => '查询成功', 'data'=> $data,'success'=>'true','timestamp'=>0]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'message' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * @param $id
     * @return \think\response\Json
     */
    public function addressListsAction($id)
    {
        try {
            $user = $this->app->userService->getUserById($id);


            $params['where'][] = ['userId', '=', $user->userId];
            $lists = $this->app->userService->getAddressLists($params, $this->page);

            $data['lists'] = [];

            if (count($lists)) {
                foreach ($lists as $key => $val) {
                    $data['lists'][] = [
                        'addressId' => $val->addressId,
                        'userId' => $val->userId,
                        'consignee' => $val->consignee,
                        'phone' => $val->phone,
                        'provinceName' => $val->province?$val->province->provinceName:'',
                        'cityName' => $val->city?$val->city->cityName:'',
                        'areaName' => $val->area?$val->area->areaName:'',
                        'address' => $val->address,
                        'createdAt' => $val->createdAt
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($lists);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * @param $id
     * @return \think\response\Json
     */
    public function creditListsAction($id)
    {
        try {
            $user = $this->app->userService->getUserById($id);


            $params['where'][] = ['userId', '=', $user->userId];
            $params['order'] = ['recordId' => 'desc'];
            $lists = $this->app->userService->getCreditLists($params, $this->page);

            $data['lists'] = [];

            if (count($lists)) {
                foreach ($lists as $key => $val) {
                    $data['lists'][] = [
                        'recordId' => $val->recordId,
                        'userId' => $val->userId,
                        'originCredit' => $val->originCredit,
                        'changeCredit' => $val->changeCredit,
                        'finalCredit' => $val->finalCredit,
                        'remark' => $val->remark,
                        'createdAt' => $val->createdAt
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($lists);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * @param $id
     * @return \think\response\Json
     */
    public function donateListsAction($id)
    {
        try {
            $user = $this->app->userService->getUserById($id);


            $params['where'][] = ['userId', '=', $user->userId];
            $params['order'] = ['userDonateId' => 'desc'];
            $lists = $this->app->userService->getDonateLists($params, $this->page);

            $data['lists'] = [];

            if (count($lists)) {
                foreach ($lists as $key => $val) {
                    $data['lists'][] = [
                        'userDonateId' => $val->userDonateId,
                        'userId' => $val->userId,
                        'organizationId' => $val->organizationId,
                        'organizationName' => $val->organization->organizationName,
                        'organizationLogo' => $val->organization->organizationLogo,
                        'donateCredit' => $val->donateCredit,
                        'createdAt' => $val->createdAt
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($lists);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    /**
     * 获取用户答题列表
     * @param $id
     * @return \think\response\Json
     */
    public function answerListsAction($id)
    {
        try {
            $user = $this->app->userService->getUserById($id);


            $params['where'][] = ['userId', '=', $user->userId];
            $params['order'] = ['userAnswerId' => 'desc'];
            $lists = $this->app->userService->getAnswerLists($params, $this->page);

            $data['lists'] = [];

            if (count($lists)) {
                foreach ($lists as $key => $val) {
                    $data['lists'][] = [
                        'userAnswerId' => $val->userAnswerId,
                        'userId' => $val->userId,
                        'questionId' => $val->questionId,
                        'questionTitle' => $val->question->questionTitle,
                        'answer' => $val->answer,
                        'isRight' => $val->isRight,
                        'isRightText' => $val->getRightText(),
                        'credit' => $val->credit,
                        'createdAt' => $val->createdAt
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($lists);

            return json(['code' => 200, 'msg' => '查询成功', 'data'=> $data]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    public function changeCreditAction($id)
    {
        try {
            $type = isset($this->post['type'])?$this->post['type']:1;
            $credit = isset($this->post['credit'])?$this->post['credit']:0;
            $remark = isset($this->post['remark'])?$this->post['remark']:'';

            if ($credit == 0) {
                throw new \Exception('请输入积分');
            }

            $user = $this->app->userService->getUserById($id);

            if ($type == 1) {
                $this->app->userCreditService->add($user, $credit, $remark);
            } else {
                $this->app->userCreditService->reduce($user, $credit, $remark);
            }

            return json(['code' => 200, 'msg' => '操作成功', 'data'=> []]);
        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    public function exportAction()
    {
        try{
            $params = $this->request->post();

            $select = $this->_get_cond($params);

            $this->app->userService->export($select);

        }catch(\Exception $e){
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data'=> []]);
        }
    }

    public function _get_cond($post)
    {
        $params = [];
        $params['where'][] = ['appletId', '=', $this->appletId];
        $params['order'] = ['userId'=>'desc'];
        $params['where'][] = ['is_delete','=',0];

        if(!empty($post['userName'])){
            $params['where'][] = ['userName','like','%'.$post['userName'].'%'];
        }

        if(!empty($post['realName'])){
            $params['where'][] = ['realName','like','%'.$post['realName'].'%'];
        }

        if(isset($post['gender']) && $post['gender']!==""){
            $params['where'][] =['gender','=',$post['gender']];
        }

        if(isset($post['status']) && $post['status']!==''){
            $params['where'][] = ['status','=',$post['status']];
        }

        if(isset($post['uniCode']) && $post['uniCode']!==''){
            $params['where'][] = ['uniCode','=', $post['uniCode']];
        }

        if(isset($post['universityId']) && $post['universityId']!==''){
            $params['where'][] = ['universityId','=', $post['universityId']];
        }

        if(isset($post['creditOrder']) && $post['creditOrder'] == 1){
            $params['order'] = ['totalCredit'=>'asc'];
        }

        if(isset($post['creditOrder']) && $post['creditOrder'] == 2){
            $params['order'] = ['totalCredit'=>'desc'];
        }

        if(isset($post['startDate']) && $post['startDate'] != ''){
            $params['where'][] = ['createdAt', '>=', $post['startDate']];
        }

        if(isset($post['endDate']) && $post['endDate'] != ''){
            $params['where'][] = ['createdAt', '<', $post['endDate'].' 23:59:59'];
        }

        return $params;
    }
}